<template>
  <div>
    <div class="container"  v-if="isList">
        <!-- 添加按钮区 -->
        <div class="btn_zone">
            <el-row style="align-items: center; text-align: center;">
                <el-col :span="1"><el-button type="primary" @click="handleAddTeacher">添加老师</el-button></el-col>
                <el-col :span="1" :push="22"><el-icon><ArrowUpBold /></el-icon></el-col>
            </el-row>
        </div>
        <el-divider />
        <!-- 表格区 -->
        <div class="tbl_zone">
            
            <el-table :data="tableData"  style="width: 100%;" size="large">
                <el-table-column fixed prop="seq" label="#" sortable width="80" />
                <el-table-column fixed prop="name" label="老师名" sortable width="150" />
                <el-table-column prop="sex" label="性别" width="100" />
                <el-table-column prop="phone" label="手机号码" sortable width="200" />
                <el-table-column prop="description" label="备注" width="480" />
                <el-table-column fixed="right" label="操作" min-width="120">
                  <template #default="scope">
                    <el-button link type="primary" @click="handleDetail(scope.row.id)">
                      查看详情&nbsp;<el-icon><InfoFilled /></el-icon>
                    </el-button>
                    <el-button link type="success" @click="handleEdit">Edit&nbsp;<el-icon><Edit /></el-icon></el-button>
                    <el-button link type="danger"  @click="handleDelete">删除&nbsp;<el-icon><Delete /></el-icon></el-button>
                  </template>
                </el-table-column>
              </el-table>

              <!-- 分页区域 -->
              <div class="pagination-container">
                <el-pagination background layout="prev, pager, next" :total="total" />
              </div>
        </div>



  <!-- 抽屉区 -->
      <el-drawer
              v-model="drawer"
              direction="rtl"
              size="50%">
          <!-- 自定义头部 --> 
          <template #header="{ titleId, titleClass }">
              <h2 :id="titleId" :class="titleClass">{{ drawerTitle }}</h2>
          </template>
          <!-- 添加表单 -->
          <el-form
              ref="teacherFormRef"
              style="max-width: 600px"
              :model="teacherForm"
              :rules="rules"
              label-width="auto"
              class="add_teacher_form"
              status-icon>
              <el-form-item label="老师姓名" prop="name">
                  <el-input v-model="teacherForm.name" />
              </el-form-item>
              <el-form-item label="手机号" prop="phone">
                  <el-input v-model="teacherForm.phone" />
              </el-form-item>
              <el-form-item label="邮箱" prop="email">
                  <el-input v-model="teacherForm.email" />
              </el-form-item>
           
              <el-form-item label="性别" prop="sex">
                  <el-radio-group v-model="teacherForm.sex">
                      <el-radio value="男">男</el-radio>
                      <el-radio value="女">女</el-radio>
                  </el-radio-group>
              </el-form-item>

             <el-form-item label="出生日期" prop="birth">
                  <el-date-picker v-model="teacherForm.birth"
                          type="date"
                          aria-label="Pick a date"
                          placeholder="选择日期"
                          style="width: 100%"/>
             </el-form-item>

             <el-form-item label="老师介绍" prop="introduce">
                  <el-input v-model="teacherForm.introduce" type="textarea" />
             </el-form-item>

             <el-form-item>
              <el-button type="primary" @click="submitForm(teacherFormRef)">
                添加
              </el-button>
              <el-button @click="resetForm(teacherFormRef)">重置</el-button>
            </el-form-item>

          </el-form>

      </el-drawer>

    </div>
    <TeacherDetail v-else   v-model:isList="isList"   :id="idd"/>
  </div>  
</template>

<script setup>
import loadJson from '@/requests/loadJson.js' 
import  { reactive, ref, onMounted,toRefs } from 'vue'
import { ElMessage } from 'element-plus'
import { useRoute, useRouter } from 'vue-router'
import TeacherDetail from '@/views/Teacher/TeacherDetail.vue'

//定义响应式对象
const tableData = ref(null)
const total = ref(10)
const isList = ref(true)

//定义异步方法来加载数据
async function fetchLocalData() {
    try {
        const data = await loadJson('demoDatas/teacher/tableData.json')
        tableData.value = data
        console.log(data,'aaaaaa')
        //获取数组的长度
        total.value = data.length
    } catch (error) {
        console.error('从loadJson.js调用时发生错误:', error)
    }
}
//调用方法
onMounted(()=> {
    console.log('页面挂载完成，加入本地json文件');
    //todo 这里需要开发人员修改，改成加载后端的数据
    fetchLocalData()
}) 

const drawer = ref(false)
const drawerTitle = ref('添加老师')

//给添加按钮添加事件处理，弹出抽屉
const handleAddTeacher = () => {
    drawer.value = true
    drawerTitle.value = '添加老师'
}

//以下是在抽屉里的按钮添加的事件和表单验证相关的操作
const teacherFormRef = ref()
const teacherForm = reactive({
    name: '',
    phone: '',
    email: '',
    sex: '',
    birth: '',
    introduce: '',
})
//表单验证规则
const rules = reactive({
  name: [
    { required: true, message: '请输入老师姓名', trigger: 'blur' },
    { min: 3, max: 6, message: '姓名长度在3-6之间', trigger: 'blur' },
  ],
  phone: [
    {
      required: true,
      message: '请输入手机号码',
      trigger: 'blur',
    },
  ],
  sex: [
    {
        required: true,
        message: '请选择性别',
        trigger: 'blur'
    }
  ],
  email: [
    {
      required: true,
      message: '请输入邮箱',
      trigger: 'blur',
    },
  ],
  birth: [
    {
      type: 'date',
      required: true,
      message: '请选择生日',
      trigger: 'change',
    },
  ],
  introduce: [
    { required: false, message: '自我介绍', trigger: 'blur' },
  ],
})

//提交和重置函数
const submitForm = async (formElement) => {
    console.log(formElement)

    if (!formElement) return
    //进行验证
    await formElement.validate((valid, fields) => {
        if (valid) {
            console.log('submit!')
            // todo 这里去提交表单数据到后端
            // ...

        } else {
            console.log('表单验证失败，请重新填写', fields)
        }
    })
}
//重置表单，这里不传参数也可以，因为我们定义了 teacherFormRef 对象
const resetForm = (formElement) => {
    if (!formElement) return
    formElement.resetFields()
}

//useRouter钩子则用来访问路由器实例本身。它返回一个路由器对象，让你能够进行导航（比如push、replace）、
//获取路由器的全局状态或添加路由守卫等功能。
const router = useRouter()

//------- 以下三个方法是处理表格中的三个按钮的，需要自行完成代码
const idd = ref()
const handleDetail = (id) => {
    //进行编程式导航
    // router.push({
    //     name: 'teacherDetail',
    //     params: {id: `${id}`}
    // }) 
    isList.value = false
    idd.value = id
   
}
const handleEdit = () => {
    //修改抽屉title
    drawerTitle.value = '修改老师'
    //打开抽屉
    drawer.value = true
    //给表单元素赋值
    teacherForm.name = '测试姓名'
    teacherForm.phone = '13899007766'
    //todo ...

}

const handleDelete = () => {
    ElMessage({
        message: '你点击了删除老师按钮',
        type: 'warning'
    })
    //todo ...
}

</script >

<style scoped>
    .pagination-container {
        margin-top: 15px;
        display: flex;
        justify-content: flex-end;
    }

    .add_teacher_form {
        margin: 10px 50px;
    }

</style>